<template>
	<view class="project-page">
		<nav-header title="项目经历"></nav-header>

		<view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
			<view class="page-title">项目经历</view>
			<view class="subtitle">展示你参与的项目和担任的角色</view>
			<!-- Edit Form Popup -->
			<view class="form-container">
				<!-- Project Name Field -->
				<view class="form-item">
					<text class="form-label required">项目名称</text>
					<input class="form-input" type="text" v-model="formData.projectName" placeholder="请输入项目名称" />
				</view>

				<!-- position Field -->
				<view class="form-item">
					<text class="form-label required">担任角色</text>
					<input class="form-input" type="text" v-model="formData.position" placeholder="请输入你在项目中担任的角色" />
				</view>

				<!-- Project Time -->
				<view class="form-item">
					<text class="form-label required">项目时间</text>
					<view class="time-range">
						<!-- Start Time -->
						<picker mode="date" :value="formatTimeForPicker(formData.startDate)" fields="month"
							@change="handleStartTimeChange">
							<view class="time-picker">
								<text>{{ formData.startDate ? formData.startDate : '开始时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>

						<text class="time-separator">至</text>

						<!-- End Time -->
						<picker mode="date" :value="formatTimeForPicker(formData.endDate)" fields="month"
							@change="handleEndTimeChange">
							<view class="time-picker">
								<text>{{ formData.endDate ? formData.endDate : '结束时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>

				<!-- projectDescription Field -->
				<view class="form-item">
					<view class=""
						style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
						<text class="form-label">项目描述</text>
						<button class="generate-btn" @click="generateProject">
							<text class="generate-icon">✨</text>
							AI生成
						</button>
					</view>
					<textarea class="form-textarea" v-model="formData.projectDescription"
						placeholder="描述项目背景、你负责的内容、使用的技术以及取得的成果等" maxlength="1000"></textarea>
					<text class="word-count">{{ formData.projectDescription ? formData.projectDescription.length : 0 }}/1000</text>
				</view>

				<!-- 底部按钮 -->
				<view class="bottom">
					<!-- Delete Button -->
					<view class="delete-action" v-if="!isAdding">
						<button class="delete-btn" @click="confirmDelete">删除</button>
					</view>
					<!-- Save Button -->
					<view class="action-bar">
						<button class="save-btn" @click="saveProject">保存</button>
					</view>
				</view>
			</view>
		</view>



		<!-- Delete Confirmation -->
		<uni-popup ref="deletePopup" type="dialog">
			<uni-popup-dialog title="删除确认" content="确定要删除这条项目经历吗？删除后将无法恢复。" :beforeClose="true" @confirm="deleteProject"
				@close="closeDeletePopup"></uni-popup-dialog>
		</uni-popup>

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popupProject" background-color="#fff" mask-background-color="rgba(0,0,0,0)"
				:is-mask-click="false" type="bottom" borderRadius='20px 20px 0 0 '>
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">AI生成</text>
						<uni-icons type="closeempty" size="24" @click="closePopupProject"></uni-icons>
					</view>
					<view class="popup-body">
						<text>{{AIContent}}</text>
					</view>
					<view class="popup-footer">
						<button class="popup-btn" @click="rewriteProject">重写</button>
						<button type="primary" class="popup-btn" @click="replaceProject">替换</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue'
	import NavHeader from '@/components/nav-header.vue'
	import ExperienceItem from '@/components/experience-item.vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		getProjectExperienceDetail,
		addProjectExperience,
		updateProjectExperience,
		deleteProjectExperience,
		generateProjectExperienceDescription
	} from '@/api/edit/project'
	import env from '@/env'
	import { useAuthStore } from '@/store/index';
	import { useResumeStore } from '@/store/resume.js'
	import { mockInterviewWebSocketProcess } from '@/api/ai'
	import { useWebSocket } from '@/utils/useWebSocket'
	
	const authStore = useAuthStore();
	const resumeStore = useResumeStore()
	const statusBarHeight = ref(20)
	const deletePopup = ref(null)
	const isAdding = ref(true)
	const currentId = ref(null)
	const currentIndex = ref(-1)
	const formData = reactive({
		projectName: '',
		position: '',
		startDate: '',
		endDate: '',
		projectDescription: ''
	})
	const AIContent = ref('')
	const popupProject = ref(null)
	const isGenerating = ref(false)
	const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)

	// 注册WebSocket消息处理函数
	onMessage((data) => {
		uni.hideLoading();
		try {
			if (typeof data === 'string') {
				try {
					const parsedData = JSON.parse(data);
					if (parsedData.topic === 'PROJECT_EXPERIENCE') {
						if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
							isGenerating.value = false;
							uni.hideLoading();
							uni.showToast({
								title: '生成完成',
								icon: 'success'
							});
							return;
						}
						AIContent.value += parsedData.content;
						return;
					}
				} catch (e) {
					// 如果不是JSON格式，直接处理字符串
					if (data === '[DONE]' || data.includes('[DONE]')) {
						isGenerating.value = false;
						uni.hideLoading();
						uni.showToast({
							title: '生成完成',
							icon: 'success'
						});
						return;
					}
					AIContent.value += data;
				}
			}
		} catch (error) {
			console.error('处理WebSocket消息出错:', error);
		}
	});

	onLoad(async (options) => {
		if (options.index) {
			isAdding.value = false
			currentId.value = options.index
			await fetchProjectDetail(options.index)
		} else {
			isAdding.value = true
			resetForm()
		}
	})

	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync()
		statusBarHeight.value = systemInfo.statusBarHeight
		
		// 启动时先尝试连接WebSocket
		try {
			connect().then(() => {
				console.log('WebSocket连接成功，可以接收消息');
			}).catch(err => {
				console.error('WebSocket连接失败:', err);
			});
		} catch (e) {
			console.error('连接WebSocket异常:', e);
		}
	})
	
	onUnload(() => {
		// 关闭WebSocket连接
		close();
		if (isGenerating.value) {
			isGenerating.value = false;
		}
	})

	function resetForm() {
		formData.projectName = ''
		formData.position = ''
		formData.startDate = ''
		formData.endDate = ''
		formData.projectDescription = ''
	}

	async function fetchProjectDetail(id) {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			const res = await getProjectExperienceDetail(id)
			if (res.code === 200 && res.data) {
				Object.assign(formData, res.data)
			}
		} catch (e) {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const handleStartTimeChange = (e) => {
		formData.startDate = e.detail.value
	}
	const handleEndTimeChange = (e) => {
		formData.endDate = e.detail.value
	}

	const saveProject = async () => {
		if (!formData.projectName.trim()) {
			uni.showToast({
				title: '请输入项目名称',
				icon: 'none'
			});
			return
		}
		if (!formData.position.trim()) {
			uni.showToast({
				title: '请输入担任角色',
				icon: 'none'
			});
			return
		}
		if (!formData.startDate) {
			uni.showToast({
				title: '请选择开始时间',
				icon: 'none'
			});
			return
		}
		if (formData.endDate && formData.startDate > formData.endDate) {
			uni.showToast({
				title: '开始时间不能晚于结束时间',
				icon: 'none'
			});
			return
		}
		try {
			uni.showLoading({
				title: '保存中...'
			})
			let res
			// TODO:修改
			const params = {
				...formData,
				resumeId:resumeStore.resumeId,
			}
			if (isAdding.value) {
				res = await addProjectExperience(params)
			} else {
				params.id = currentId.value
				res = await updateProjectExperience(params)
			}
			if (res.code === 200) {
				uni.showToast({
					title: isAdding.value ? '添加成功' : '更新成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '保存失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	const confirmDelete = () => {
		deletePopup.value.open()
	}
	const closeDeletePopup = () => {
		deletePopup.value.close()
	}
	const deleteProject = async () => {
		if (!currentId.value) return
		try {
			uni.showLoading({
				title: '删除中...'
			})
			const res = await deleteProjectExperience(currentId.value)
			if (res.code === 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '删除失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	const formatTime = (timeStr) => {
		if (!timeStr) return ''
		return timeStr.replace(/(\d{4})-(\d{2})/, '$1年$2月')
	}
	const formatTimeForPicker = (timeStr) => {
		return timeStr || ''
	}

	// 使用AI生成项目经历
	const generateProject = async () => {
		try {
			// 避免重复请求
			if (isGenerating.value) {
				return;
			}
			
			isGenerating.value = true;
			AIContent.value = ''; // 清空之前的内容
			popupProject.value.open();
			
			uni.showLoading({
				title: 'AI生成中...'
			});
			
			// 创建请求数据
			const requestData = {
				type: 'PROJECT_EXPERIENCE',
				aiResumeProjectExperienceBo: {
					resumeId: resumeStore.resumeId,
					projectName: formData.projectName,
					position: formData.position,
					startDate: formData.startDate,
					endDate: formData.endDate,
				}
			};
			
			// 检查WebSocket连接状态
			if (!isConnected.value) {
				console.log('WebSocket未连接，尝试连接...');
				await connect();
				console.log('WebSocket连接已建立');
			} else {
				console.log('WebSocket已连接，状态正常');
			}
			
			// 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
			console.log('准备调用HTTP接口触发后端推送...');
			
			// 调用HTTP接口触发后端推送WebSocket消息
			mockInterviewWebSocketProcess(requestData).then(res => {
				// 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
				setTimeout(() => {
					if (isGenerating.value && !AIContent.value) {
						console.log('未收到WebSocket消息，使用传统方式');
					}
				}, 5000); // 5秒后检查
				
			}).catch(err => {
				console.error('调用HTTP接口失败:', err);
				isGenerating.value = false;
				uni.hideLoading();
				uni.showToast({
					title: '生成失败',
					icon: 'none'
				});
			});
			
		} catch (error) {
			console.error('生成项目经历失败', error);
			isGenerating.value = false;
			uni.hideLoading();
			uni.showToast({
				title: '生成失败',
				icon: 'none'
			});
		}
	}

	// 关闭AI生成弹窗
	const closePopupProject = () => {
		popupProject.value.close();
		isGenerating.value = false;
		uni.hideLoading();
	}

	// 重写AI生成内容
	const rewriteProject = () => {
		isGenerating.value = false;
		setTimeout(() => {
			generateProject();
		}, 300);
	}

	// 替换AI生成内容
	const replaceProject = () => {
		popupProject.value.close();
		formData.projectDescription = AIContent.value;
		isGenerating.value = false;
	}
</script>

<style lang="scss" scoped>
	.project-page {
		min-height: 100vh;
		background-color: #FFFFFF;
		padding-bottom: 70px;

		.content {
			padding: 20px;

			.page-title {
				font-size: 24px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}

			.subtitle {
				font-size: 14px;
				color: #999;
				margin-bottom: 24px;
			}

			.experience-list {
				margin-bottom: 20px;

				.experience-item-wrap {
					margin-bottom: 16px;
				}
			}

			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 40px 0;

				.empty-icon {
					width: 120px;
					height: 120px;
					margin-bottom: 16px;
				}

				.empty-text {
					font-size: 15px;
					color: #999;
					text-align: center;
				}
			}

			.add-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 50px;
				background-color: #f5f5f5;
				border-radius: 8px;
				margin-top: 16px;

				.add-icon {
					font-size: 20px;
					color: #333;
					margin-right: 6px;
				}

				.add-text {
					font-size: 16px;
					color: #333;
				}
			}
		}

		.form-container {
			background-color: #fff;
			border-radius: 12px 12px 0 0;
			padding-bottom: 20px;

			.form-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 16px;
				border-bottom: 1px solid #f0f0f0;

				.form-title {
					font-size: 16px;
					font-weight: 500;
				}

				.close-btn {
					font-size: 24px;
					color: #999;
					width: 36px;
					height: 36px;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.form-content {
				max-height: 70vh;
				padding: 16px;
			}

			.form-item {
				margin-bottom: 24px;

				.form-label {
					display: block;
					font-size: 16px;
					color: #333;
					margin-bottom: 10px;
					font-weight: 500;

					&.required:after {
						content: '*';
						color: #ff4d4f;
						margin-left: 4px;
					}
				}

				.form-input {
					height: 44px;
					border-bottom: 1px solid #e5e5e5;
					padding: 0 12px;
					display: flex;
					align-items: center;
					font-size: 16px;
				}

				.form-textarea {
					height: 160px;
					border: 1px solid #e5e5e5;
					border-radius: 4px;
					padding: 12px;
					font-size: 15px;
				}

				.word-count {
					text-align: right;
					font-size: 12px;
					color: #999;
					display: block;
					margin-top: 4px;
				}

				.picker-arrow {
					margin-left: auto;
					font-size: 12px;
					color: #999;
				}

				.time-range {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.time-picker {
						flex: 1;
						height: 44px;
						border-bottom: 1px solid #e5e5e5;
						display: flex;
						align-items: center;
						font-size: 16px;

						&.disabled {
							opacity: 0.6;
						}
					}

					.time-separator {
						padding: 0 15px;
						color: #666;
					}
				}
			}

			.switch-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.form-actions {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				background-color: #fff;
				padding: 10px 20px;
				box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
				z-index: 9;

				.cancel-btn,
				.save-btn {
					flex: 1;
					height: 44px;
					line-height: 44px;
					text-align: center;
					border-radius: 22px;
					font-size: 16px;
				}

				.cancel-btn {
					background-color: #f5f5f5;
					color: #666;
					margin-right: 12px;
				}

				.save-btn {
					width: 100%;
					height: 44px;
					line-height: 44px;
					background-color: #5ac725;
					color: #FFFFFF;
					font-size: 16px;
					font-weight: 500;
					border-radius: 22px;
				}
			}

			.delete-action {

				.delete-btn {
					width: 100%;
					height: 44px;
					line-height: 44px;
					text-align: center;
					border-radius: 22px;
					font-size: 16px;
					color: #ff4d4f;
					background-color: #fff;
					border: 1px solid #ff4d4f;
				}
			}
		}
	}

	.action-bar {
		flex: 1;

		.save-btn {
			width: 100%;
			height: 44px;
			line-height: 44px;
			background-color: #5ac725;
			color: #FFFFFF;
			font-size: 16px;
			font-weight: 500;
			border-radius: 22px;
		}
	}

	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 70px;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 20px;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
		z-index: 9;
		gap: 30rpx;
	}

	.delete-action {
		.delete-btn {
			width: 100%;
			height: 44px;
			line-height: 44px;
			text-align: center;
			border-radius: 22px;
			font-size: 16px;
			color: #ff4d4f;
			background-color: #fff;
			border: 1px solid #ff4d4f;
		}
	}
</style>